package xcommand

import (
	"git-agent/utils/xlog"
	"os"
	"os/exec"
	"time"
)

type Cmd struct {
	Dir string
	//先执行的命令
	Before []string
	//初始化命令
	Init []string
	//最后执行的命令
	After []string
}

func New() *Command  {
	return &Command{
		cmds: map[string]*Cmd{},
	}
}
type Command struct {
	cmds map[string]*Cmd
}

func (this *Command) AddCmd(project string, cmd *Cmd)  {
	this.cmds[project] = cmd
}

func (this *Command) getCmd(project string) *Cmd  {
	var cmd *Cmd
	var ok bool
	if cmd, ok = this.cmds[project]; ok == true {
		return cmd
	}
	return nil
}
func (this *Command) ExecBeforeCmd(project string) bool  {
	cmd := this.getCmd(project)
	if cmd == nil || cmd.Before == nil || len(cmd.Before) == 0 {
		return true
	}
	return this.exec(cmd.Dir, cmd.Before)
}

func (this *Command) ExecInitCmd(project string) bool  {
	cmd := this.getCmd(project)
	if cmd == nil || cmd.Init == nil || len(cmd.Init) == 0 {
		return true
	}
	return this.exec(cmd.Dir, cmd.Init)
}

func (this *Command) ExecAfterCmd(project string) bool  {
	cmd := this.getCmd(project)
	if cmd == nil || cmd.After == nil || len(cmd.After) == 0 {
		return true
	}
	return this.exec(cmd.Dir, cmd.After)
}
func (this *Command) exec(dir string, args []string) bool  {
	xlog.Info.Println("[Cmd] ", args)
	cmd := exec.Command(args[0], args[1:]...)
	cmd.Dir = dir
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	// 运行命令
	if err := cmd.Start(); err != nil {
		xlog.Error.Println(err)
		return false
	}
	return true
}

func main()  {
	cmds := New()
	cmds.AddCmd("EEE", &Cmd{
		Before: []string{"ls", "-la"},
		Init:   []string{"ls", "-la"},
		After:  []string{"ls", "-la"},
	})

	cmds.ExecAfterCmd("EEE")
	time.Sleep(time.Hour)
}